import java.util.concurrent.*;

/**
 * Create by chenhd on 2021/8/28.
 * 方法十：使用FutureTask
 */
public class ConcurrentTask10 {
    public String str;

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        ConcurrentTask10 concurrentTask = new ConcurrentTask10();
        //注意：生产环境中慎用这种直接用工具类创建的方法，因为他可能使用了无界队列、拒绝策略、线程工厂类不是你想要的，除非你明确知道就是你想要的
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Callable<String> callable = () -> {
            concurrentTask.putStr();
            return "ok";
        };
        //这次我们使用Callable，当然这里仍然可以继续用Runnable
        FutureTask<String> futureTask = new FutureTask<>(callable);
        executorService.submit(futureTask);
        String result = futureTask.get();
        System.out.println(concurrentTask.getStr());
        //不关闭线程池，主线程不会退出
        executorService.shutdown();
    }

    public void putStr() {
        try {
            TimeUnit.SECONDS.sleep(5);
            this.str = "hello concurrent.";
        } catch (InterruptedException e) {
            //log error
            e.printStackTrace();
        }
    }

    public String getStr() {
        return str;
    }
}
